package com.fy.sys.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fy.core.enums.ApiErrorEnum;
import com.fy.core.exception.ServiceException;
import com.fy.core.util.JWTUtil;
import com.fy.core.vo.ApiRest;
import com.fy.sys.entity.Logininfor;
import com.fy.sys.entity.User;
import com.fy.sys.mapper.LogininforMapper;
import com.fy.sys.mapper.UserMapper;
import com.fy.sys.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author hxd
 * @since 2023-06-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininforMapper logininforMapper;
    @Resource(name = "getAsyncExecutor")
    private ThreadPoolTaskExecutor executor;
    @Override
    public ApiRest login(User user,String code,String id,String userAgent) {
        /*1.参数校验*/

        /*2.校验验证码*/
        verifyCode(code,id);

        /*3.校验账号是否合法*/
        User userDB = verifyUser(user);

        /*4.颁发令牌*/
        userDB.setPassword("");
        String token = JWTUtil.generatorMinutesToken(userDB, 30);

        /*记录用户的登录情况*/
        executor.execute(()->{
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Logininfor logininfor=new Logininfor();
            logininfor.setUserName(user.getUserName());
            logininfor.setLoginTime(new Date());
            UserAgent parse= UserAgentUtil.parse(userAgent);
            /*logininfor.setIpaddr();*/
            logininfor.setBrowser(parse.getBrowser().getName());
            logininfor.setOs(parse.getOs()+"");
            logininforMapper.insert(logininfor);
        });


        return ApiRest.success(token);
    }

    private void verifyCode(String code, String id) {
        Map map = userMapper.selectCodeById(id);
        String  codedDB = (String) map.get("code");
        if (StringUtils.isEmpty(codedDB)){
            throw new ServiceException(ApiErrorEnum.LOGIN_INVALID_MSG);
        }
        if (!code.equals(codedDB)){
            throw new ServiceException(ApiErrorEnum.LOGIN_INVALID_MSG);
        }
    }

    private User verifyUser(User user) {
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getUserName,user.getUserName());
        User userDB = this.baseMapper.selectOne(userQueryWrapper);
        if (userDB==null){
            throw new ServiceException(ApiErrorEnum.LOGIN_USERNAME_PASSWORD_INVALID);
        }
        //比较密码
        if (!DigestUtil.bcryptCheck(user.getPassword(),userDB.getPassword())){
            throw new ServiceException(ApiErrorEnum.LOGIN_USERNAME_PASSWORD_INVALID);
        }
        return userDB;
    }

    public static void main(String[] args) {
        //注册
        String bcrypt = DigestUtil.bcrypt("123");
        System.out.println("bcrypt = " + bcrypt);

        //$2a$10$4JTtH.pX7W/7AFWJdouepOpAWWpkhWYw8YbS2RMq6X6RdtVX3lN0q
        String pwdDB="$2a$10$4JTtH.pX7W/7AFWJdouepOpAWWpkhWYw8YbS2RMq6X6RdtVX3lN0q";
        boolean b = DigestUtil.bcryptCheck("1234", pwdDB);
        System.out.println("b = " + b);
    }
}
